const express = require("express");
const router = express.Router();
const OperationLog = require("../db/OperationLog");
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
const ejsExcel = require("ejsexcel");
const fs = require("fs");
const logger = require("../common/logger");
const authhs256 = require("../middlewares/authhs256/authentication")
const Fun = require("../middlewares/Fun")
/**
 * 日志的增删改查
 */
//添加
var a = 1;
router.post("/save", authhs256.ensureAuthenticated, (req, res) => {
    let logs = req.body;
    let { _id, name, roles } = req.user;
    // let pare = {
    //     id: a++,
    //     name: a++,
    //     roles: a++,
    //     ip: req.ip.replace(/::ffff:/, ''),
    //     time: now(),
    //     Operationcontent: "操作成功"
    // };
    logs.id = _id;
    logs.name = name;
    logs.roles = roles;
    logs.ip = req.ip.replace(/::ffff:/, '');
    logs.time = now();
    let operationLog = new OperationLog(logs);
    operationLog.save().then(data => {
        return res.json({
            code: 200,
            msg: "保存成功!"
        })
    }).catch(err => {
        return res.json({
            code: 201,
            msg: "发生错误!"
        })
    })
});

//删除
router.post("/delete", authhs256.ensureAuthenticated, (req, res) => {
    let { _id } = req.body;
    if (!_id) {
        return res.json({
            code: 201,
            msg: "缺少必要参数"
        })
    }
    OperationLog.findOne({ _id }).then(data => {
        if (data) {
            if (data.name) {
                return data.remove().then(data => {
                    return res.json({
                        code: 200,
                        msg: "删除成功!"
                    })
                })
            } else {
                return res.json({
                    code: 201,
                    msg: "删除失败!"
                })
            }
        } else {
            return res.json({
                code: 201,
                msg: "没有要查询的数据!"
            })
        }
    }).catch(err => {
        return res.json({
            code: 201,
            msg: "发生错误!"
        })
    })

});

//查询搜索
router.post("/find", authhs256.ensureAuthenticated, (req, res) => {
    const pageindex = Number(req.body.pageindex) || 1;
    const pagesize = Number(req.body.pagesize) || 20;
    const starttime = req.body.starttime;
    const endtime = req.body.endtime;
    let query = {};
    let searchs = req.body;
    if (starttime || endtime) {
        query = { time: { $gte: starttime + " 00:00:00", $lte: endtime + " 24:00:00" } }
    };
    if (searchs.text) {
        const regs = new RegExp(searchs.text)
        if (req.body.results == 1) {
            query = { $or: [{ name: { $regex: regs } }] }
        } else {
            query = { $or: [{ Operationcontent: { $regex: regs } }] }
        }
    }
    OperationLog.count(query).then(counts => {
        return OperationLog.find(query).sort({ time: -1 }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(data => {
            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "查询日志成功");
            return res.json({
                code: 200,
                counts,
                data,
                msg: "查询成功!"
            })
        })
    }).catch(err => {
        Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "查询日志失败")
        return res.json({
            err,
            code: 201,
            msg: "发生错误!"
        })
    })
});

//操作日志导出Excel表格
router.post("/downloadExcel", authhs256.ensureAuthenticated, (req, res) => {
    let pageindex = req.body.pageindex;
    let pagesize = req.body.pagesize;
    let starttime = req.body.starttime;
    let endtime = req.body.endtime;
    let query = {};
    let searchs = req.body;
    if (starttime || endtime) {
        query.time = { $gte: `${starttime} 00:00:00`, $lte: `${endtime} 24:00:00` }
    };
    if (searchs.text) {
        query.$text = { $search: searchs.text }
    }
    if (req.body.arr) {
        starttime = null;
        endtime = null;
        query = { _id: { $in: JSON.parse(req.body.arr) } }
    };
    if (pageindex || pagesize) {
        OperationLog.count(query).then(counts => {
            return OperationLog.find(query).sort({ time: 1 }).sort({ time: -1 }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).then(data => {
                return data
            })
        }).then(datas => {
            let data = []
            let exlBuf;
            if (starttime || endtime) {
                //获得Excel模板的buffer对象
                exlBuf = fs.readFileSync(__dirname + "/../template.xlsx");
                data.push(`${starttime} 00:00:00-${endtime} 24:00:00`)
                data.push(datas)
            } else {
                //获得Excel模板的buffer对象
                exlBuf = fs.readFileSync(__dirname + "/../template.xlsx");
                data.push("")
                data.push(datas)
                // exlBuf = fs.readFileSync(__dirname + "/../template2.xlsx");
                // data = datas
            }
            let name = moment().format('YYYYMMDDHHmmss');
            //用数据源(对象)data渲染Excel模板
            return ejsExcel.renderExcel(exlBuf, data).then((exlBuf2) => {
                fs.writeFileSync(`./${name}.xlsx`, exlBuf2);
                return name;
            })
        }).then(name => {
            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "下载日志成功")
            return res.json({
                code: 200,
                downloadExcel: name
            })
        }).catch(err => {
            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "查询日志失败")
            return res.json({
                err,
                code: 201,
                msg: "发生错误!"
            })
        })
    } else {
        OperationLog.count(query).then(counts => {
            return OperationLog.find(query).sort({ time: -1 }).then(data => {
                return data
            })
        }).then(datas => {
            let data = []
            let exlBuf;
            if (starttime || endtime) {
                //获得Excel模板的buffer对象
                exlBuf = fs.readFileSync(__dirname + "/../template.xlsx");
                data.push(`${starttime} 00:00:00-${endtime} 24:00:00`)
                data.push(datas)
            } else {
                //获得Excel模板的buffer对象
                exlBuf = fs.readFileSync(__dirname + "/../template.xlsx");
                data.push("")
                data.push(datas)
                // exlBuf = fs.readFileSync(__dirname + "/../template2.xlsx");
                // data = datas
            }
            let name = moment().format('YYYYMMDDHHmmss');
            //用数据源(对象)data渲染Excel模板
            return ejsExcel.renderExcel(exlBuf, data).then((exlBuf2) => {
                fs.writeFileSync(`./${name}.xlsx`, exlBuf2);
                return name;
            })
        }).then(name => {
            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "下载日志成功")
            return res.json({
                code: 200,
                downloadExcel: name
            })
        }).catch(err => {
            Fun.saveLogs(req.user, req.ip.replace(/::ffff:/, ''), "查询日志失败")
            return res.json({
                err,
                code: 201,
                msg: "发生错误!"
            })
        })
    }
});

//下载
router.get("/download", (req, res) => {
    let name = req.query.name
    if (!name) {
        return res.json({
            code: 201,
            msg: "缺少参数"
        })
    }
    if (fs.existsSync(`./${name}.xlsx`)) {//判断文件夹是否存在
        return res.download(`./${name}.xlsx`, `${name}.xlsx`, function (err) {
            if (!err) {
                fs.unlink(`./${name}.xlsx`, () => { });//删除文件
                logger.info("下载日志成功....")
            } else {
                fs.unlink(`./${name}.xlsx`, () => { });//删除文件
                logger.info("下载日志失败!")
            }
        });
    } else {
        return res.json({
            code: 201,
            msg: "下载失败或者文件不存在!"
        })
    }
})



module.exports = router;